var fs = require("fs");
const cachePath = "C:/Users/Administrator/Desktop/m3u8/seo/";

const sets = new Set();

const exists = (path) => {
    if (sets.has(path)) {
        return true;
    }
    if (fs.existsSync(path)) {
        sets.add(path);
        return true;
    }
    return false;
};

const cacheAllPaths = (path) => {
    if (!exists(path)) {
        return [];
    }
    const subPaths = fs.readdirSync(path).map((file) => {
        return `${path}/${file}`;
    });
    subPaths.forEach((subPath) => {
        if (fs.lstatSync(subPath).isDirectory()) {
            cacheAllPaths(subPath);
        }
    });
    return Array.from(sets);
};


//  /   /home   /distile  /distile?bookId=abc  /afd/inde.html
const uriToPath = (uri) => {
    if (uri.includes("?")) {
        let u = uri.split("?");
        return cachePath + u[0] + "/";
    }
    let uris = uri.split("/")
    if (uris.length > 2) {
        return cachePath + uris.slice(0, -1).join('/') + "/";
    } else {
        return cachePath;
    }
}

const uriToFileName = (uri) => {
    if (uri.includes("?")) {
        let u = uri.split("?");
        return u[1];
    }
    let uris = uri.split("/")
    if (uris.length > 1) {
        return uris[uris.length - 1];
    } else {
        return "undifind";
    }
}

cacheAllPaths(cachePath);

module.exports = {
    uriToPath,
    uriToFileName,
    exists
}